package com.example.Dao;

import com.example.pojo.User;
import com.example.utils.ConnUtils;
import com.example.utils.DataUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDao {
    public User getUser(User user){
        User u =null;
        //链接数据库
        Connection conn = DataUtils.getConn();
//        编写SQL
        String sql ="select * from user where userId=? and userPwd=?";
        try {
//            获取预编译的对象，PreparedStatement
            PreparedStatement pst = conn.prepareStatement(sql);
//            给占位符赋值，执行sql
            pst.setString(1, user.getUserId());
            pst.setString(2, user.getUserPwd());
            ResultSet rs =pst.executeQuery();//executeQuery()执行查询，executeUpdate()执行增删改；
//            把数据封装成集合
            if(rs.next()){
                u =new  User(
                        rs.getString(1),
                        rs.getString(2),
                        rs.getString(3),
                        rs.getString(4)
                        );
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            DataUtils.closeConnection(conn);
        }
        return  u;
    }
    public int  insertUser( User user){
        int flag =0;
        Connection conn =DataUtils.getConn();
        String sql ="INSERT INTO user VALUES(?,?,?,?)";
        try {
            PreparedStatement pst= conn.prepareStatement(sql);
            pst.setString(1,user.getUserId());
            pst.setString(2,user.getUserPwd());
            pst.setString(3,user.getUserAvtor());
            pst.setString(4,user.getUserPhone());
            flag = pst.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException(e);

        }finally {
            DataUtils.closeConnection(conn);
        }
        return flag;
    }public int  deleteUser( User user){
        int flag =0;
        Connection conn =DataUtils.getConn();
        String sql ="DELETE FROM user WHERE userId=?";
        try {
            PreparedStatement pst= conn.prepareStatement(sql);
            pst.setString(1,user.getUserId());
            flag = pst.executeUpdate();

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            DataUtils.closeConnection(conn);
        }
        return flag;
    }
    public int  UpdateUser( User user){
        int flag =0;
        Connection conn =DataUtils.getConn();
        String sql ="UPDATE user SET userPwd =? WHERE userId =?";
        try {
            PreparedStatement pst= conn.prepareStatement(sql);
            pst.setString(2,user.getUserId());
            pst.setString(1,user.getUserPwd());
            flag = pst.executeUpdate();

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            DataUtils.closeConnection(conn);
        }
        return flag;
    }
}
